package cn.wzptsoft.tinymallbe.controller;

import cn.wzptsoft.common.utils.BeanConverter;
import cn.wzptsoft.common.utils.PageData;
import cn.wzptsoft.common.utils.Result;
import cn.wzptsoft.tinymallbe.entity.Sku;
import cn.wzptsoft.tinymallbe.entity.Spu;
import cn.wzptsoft.tinymallbe.entity.Theme;
import cn.wzptsoft.tinymallbe.service.SpuService;
import cn.wzptsoft.tinymallbe.service.ThemeService;
import cn.wzptsoft.tinymallbe.vo.SpuBriefVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Positive;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("spu")
public class SpuController {
    @Autowired
    private SpuService spuService;

//    SPU商品
    @GetMapping("/page")
    public Result<PageData<SpuBriefVO>> getSpuByPage(
            @RequestParam(defaultValue = "0") Integer start,
            @RequestParam(defaultValue = "10") Integer count){
        int pageNum=start/count;
        Page<Spu> pageResult = spuService.getSpuByPage(pageNum, count);
        List<SpuBriefVO> simplePageResult = BeanConverter.convert(pageResult.getContent(), SpuBriefVO.class);
        PageData<SpuBriefVO> pageDataResult = new PageData<>(simplePageResult, pageResult.getTotalElements());

        return Result.ok(pageDataResult);
    }

//    查找指定商品的详情
    @GetMapping("/detail/{id}")
    public Result<Optional<Spu>> getDetail(@PathVariable @Positive Long id){
        Optional<Spu> spu = spuService.getSpu(id);
        return Result.ok(spu);
    }

//    查找指定商品分类下的商品
    @GetMapping("/category/{id}")
    public Result<PageData<SpuBriefVO>> getByCategory(@PathVariable Long id,
                                                      @RequestParam(defaultValue = "false") Boolean isRoot,
                                                      @RequestParam(defaultValue = "0") Integer start,
                                                      @RequestParam(defaultValue = "10") Integer count){
        int pageNum=start/count;
        Page<Spu> pageResult = spuService.getByCategory(id,isRoot,pageNum,count);
        List<SpuBriefVO> simplePageResult = BeanConverter.convert(pageResult.getContent(), SpuBriefVO.class);
        PageData<SpuBriefVO> pageData = new PageData<>(simplePageResult, pageResult.getTotalElements());
        return Result.ok(pageData);
    }

}
